package com.littleken.sellproject.controller;

import com.littleken.sellproject.VO.ProductInfoVO;
import com.littleken.sellproject.VO.ProductVO;
import com.littleken.sellproject.VO.ResultVO;
import com.littleken.sellproject.model.ProductCategory;
import com.littleken.sellproject.model.ProductInfo;
import com.littleken.sellproject.service.ProductCategoryService;
import com.littleken.sellproject.utils.JsonData;
import com.littleken.sellproject.service.ProductInfoService;
import lombok.*;
import org.codehaus.jackson.map.util.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Resource
    private ProductInfoService productService;

    @Resource
    private ProductCategoryService categoryService;

    /**
     * 查询所有上架物品信息
     */
    @GetMapping("/list")
    @Cacheable(cacheNames = "product",key = "123")//缓存
                                                //两边的cachename和key要一模一样
    public ResultVO getProductInfoList(){
        //查询所有上架商品
        //productInfoList 上架商品列表
        List<ProductInfo> productInfoList = productService.findUpAll();

        //查询类目
        //categoryTypeList 提取所有上架商品类目
        //productCategoryList 相同类目列表
        List<Integer> categoryTypeList = productInfoList.stream()
                .map(e -> e.getCategoryType())
                .collect(Collectors.toList());
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);

        //数据拼装
        List<ProductVO> productVOList = new ArrayList<>();
        for(ProductCategory productCategory : productCategoryList){
            ProductVO productVO =  new ProductVO();
            productVO.setCategoryType(productCategory.getCategoryType());
            productVO.setCategoryName(productCategory.getCategoryName());

            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo : productInfoList){
                if(productInfo .getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo,productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }
        return ResultVO.success(productVOList,"成功");
    }

}
